package com.agregatesdk.core;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.reflect.Array;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import android.util.Log;

/**
 * Created by StarCite. User: andy.song Date: Apr 13, 2010 Time: 11:49:17 PM To
 * change this template use File | Settings | File Templates.
 */
public class Utils {

    public static final String Empty_Oid_Value = "NA";
    public static final String Empty_CorrelationId = "NA";
    public static final String Empty_Executed_Escalation_Type = "NA";
    public static final String LINE_SEPERATOR = System.getProperty("line.separator");

    protected static String hostAddress;

    private static String serverName;

    protected static String serverUniqueId;

    static Object parkObject = new Object();

    @Deprecated
    public synchronized static void timeWait(long waitMilliseconds) throws InterruptedException {

        synchronized (parkObject) {
            TimeUnit unit = TimeUnit.MILLISECONDS;
            unit.timedWait(parkObject, waitMilliseconds);
        }
    }

    public static boolean isNullOrEmpty(Collection<?> val) {
        return val == null || val.isEmpty();
    }

    public static boolean isNullOrEmpty(Map<?, ?> map) {
        return map == null || map.isEmpty();
    }

    public static String getLocalNetAddress() {
        if (hostAddress == null) {

            try {
                hostAddress = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                return "127.0.0.1";
            }
        }

        return hostAddress;
    }

    public static String getLocalServerName() {
        if (serverName == null) {
            try {
                serverName = InetAddress.getLocalHost().getHostName();
            } catch (Exception e) {
                return "";
            }
        }
        return serverName;
    }

    public static String getUniqueId() {
        return String.valueOf(System.nanoTime());
    }

    public static String outputStackTrace(Throwable ex) {
        String returnValue = "";

        ByteArrayOutputStream bos = null;
        PrintStream ps = null;
        try {
            bos = new ByteArrayOutputStream();
            ps = new PrintStream(bos, true);
            ex.printStackTrace(ps);

            ps.flush();
            bos.flush();

            returnValue = bos.toString();
        } catch (Exception ext) {
            // Swallow
        } finally {
            if (ps != null) {
                ps.close();
            }

            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                }
            }
        }

        return returnValue;
    }

    /**
     * Check-in for the string check from the null to the empty.
     * 
     * @param
     * */
    public static String nullToEmpty(String string) {
        if (string == null)
            return "";
        return string;
    }

    /**
     * 
     * Automatically to add one length for given array
     * 
     * @param array
     * @return
     */
    public static Object addArrayLength(Object array) {
        Class cl = array.getClass();
        if (!cl.isArray())
            return null;
        Class componentType = cl.getComponentType();
        int length = Array.getLength(array);
        int newLength = length + 1;
        Object newArray = Array.newInstance(componentType, newLength);
        System.arraycopy(array, 0, newArray, 0, length);
        return newArray;
    }

    public static boolean isNullorEmpty(String str) {
        boolean result = false;

        if (str == null || "".equals(str.trim())) {
            result = true;
        }

        return result;
    }

    
    public static int convertToScreenPixels(int dipPixels, double density) {
        return (int) convertToScreenPixels((double) dipPixels, density);
    }
    
    private static double convertToScreenPixels(double dipPixels, double density) {
        return density > 0.0D ? dipPixels * density : dipPixels;
    }

    public static String generateToken(String servertime) {
        String result = null;
        try {
            StringBuilder sb = new StringBuilder();

            sb.append(UserAccount.getInstance().getDeviceid()).append("|").append(servertime);
            char [] targetArray = MD5Checksum.getChecksum4String(sb.toString()).toCharArray();
            char [] randomArray1 = UUID.randomUUID().toString().toCharArray();
            char [] randomArray2 = UUID.randomUUID().toString().toCharArray();
            
            StringBuilder tmpArray = new StringBuilder();
            for (int i = 0; i < 32; i++) {
                tmpArray.append(randomArray1[i]).append(randomArray2[i]).append(targetArray[i]);
            }
            if (tmpArray.length() == 96) {
                result = tmpArray.substring(48, 96) + tmpArray.substring(0, 48);
            }
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return result;
    }
}
